<?php
namespace Home\Controller;
use Think\Controller;

class GrouponController extends CommonController {
	public function  _initialize(){
		parent::_initialize();
		$this->commodityLimitSrv = D('CommodityLimit');
		$this->commoditySrv = D('CommodityInfo');
		$this->commoditySrv->ini();
		$this->grouponSrv = D('GrouponInfo');
    }
	
	
	public function ajaxGetGponInfo() {
		$set_id = num_f(I('set_id'));
		if(empty($set_id)){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '参数异常';
			$this->ajaxReturn($response);
		}
		$gpon_id = num_f(I('gpon_id'));
		// 团购静态信息
		$setting = D('GrouponSetting');
		$gponInfo = D('GrouponInfo');
		$gi = $gponInfo->where("set_id = '".$set_id."' and gpon_id = '".$gpon_id."'")->find();
		if(empty($gi)) $gpon_id = null;
		$set_info = $setting->where("set_id = ".$set_id)->find();
		if(empty($set_info)){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '没有找到配置';
			$this->ajaxReturn($response);
		}
		$set_info['set_logo'] = C('HTTP_IMG').$set_info['set_logo'];
		$set_info['set_pic_url'] = $this->formatImgs($set_info['set_pic_url']);
		$set_info['set_commodity_desc'] = $this->formatImgs($set_info['set_commodity_desc']);
		$commodity_info = $this->commoditySrv->commodity_info($set_info['commodity_id']);
		$set_info['commodity_info'] = $commodity_info;
		$set_info['sale_cycle'] = $this->commoditySrv->hitLastSaleCycle($set_info['commodity_id']);
		unset($set_info['dispatch_date']);
		// 团购动态信息： 登录状态 团员列表 命中价格 
		$extend_info = array();
		$extend_info['is_login'] = 0;
		$extend_info['user_list'] = array();
		$extend_info['hit_price'] = -1;
		$extend_info['page'] = 'build_page';
		$extend_info['groupon_price'] = $gponInfo->hitGponPrice($set_info['price_gradient'],num_f($set_info['people_limit']));
		if(!empty($gpon_id)){
			$extend_info['user_list'] = $gponInfo->getGponUserList($gpon_id);
			$extend_info['hit_price'] = $gponInfo->hitGponPrice($set_info['price_gradient'],count($extend_info['user_list']));
			$extend_info['page'] = 'join_page';
		}
		if($this->checkLogin()==true){//登录
			$extend_info['is_login'] = 1;
			$extend_info['gpon_status'] = $gponInfo->getUserStatus($this->uId(),$gpon_id,$set_id);
		}else{//没有登录
			$extend_info['gpon_status'] = 1;
		}
		// 查看库存
		$commodityLimit = D('CommodityLimit');
		$limit_res = $commodityLimit->checkLimit($set_info['commodity_id'],1,2);
		if($limit_res == false){
			$extend_info['gpon_status'] = 20;//售罄
		}
		if($set_info['death_time']<date("Y-m-d H:i:s")){
			$extend_info['gpon_status'] = 22;//过期
		}
		$extend_info['check_limit_res'] = $limit_res;
		//分享文案
		if($set_id==3){
			$share_title = '食市第一喜—邀约陈奕迅';
		}else if($set_id==4){
			$share_title = '食市第二喜—苹果健康甜蜜礼';
		}else{
			$share_title = '食市';
		}
		$extend_info['share_title'] = $share_title;
		$response['data']['set_info'] = $set_info;
		$response['data']['extend_info'] = $extend_info;
		$response['msg'] = '获取成功';
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}
	
	// 建团
	public function ajaxBuildGpon() {
		if($this->checkLogin()==false){
			$response['msg'] = '尚未登陆';
			$response['toLogin'] = 1;
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id = $this->uId();
		$set_id = I('set_id');
		//建团之前的验证： 团购配置状态 团购有效时间 是否达到建团上限
		$setting = D('GrouponSetting');
		$set_info = $setting->where("set_id = ".$set_id." and status = 1")->find();
		if(empty($set_info)){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '该团购已经下线.';
			$this->ajaxReturn($response);
		}
		if(!empty($set_info['start_time'])&&date("Y-m-d H:i:s")<$set_info['start_time']){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '团购尚未开始..';
			$this->ajaxReturn($response);
		}
		if(empty($set_info['death_time']) || date("Y-m-d H:i:s")>$set_info['death_time']){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '团购已经结束...';
			$this->ajaxReturn($response);
		}
		$gponInfo = D('GrouponInfo');
		$db_res = $gponInfo->where("set_id = ".$set_id." and organiser = '".$user_id."'")->select();
		if(count($db_res)>=num_f($set_info['max_build'])){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '建团失败，您已经超过建团限额';
			$this->ajaxReturn($response);
		}
		//验证通过开始建团
		$gpon_id = $gponInfo->buildGpon($user_id,$set_id);
		$response['data'] = $gpon_id;
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$response['msg'] = '建团成功';
		$this->ajaxReturn($response);
		
	}
	
	// 参团
	public function ajaxJoinGpon() {
		if($this->checkLogin()==false){
			$response['msg'] = '尚未登陆';
			$response['toLogin'] = 1;
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id = $this->uId();
		$set_id = I('set_id');
		$gpon_id = I('gpon_id');
		if(empty($set_id) || empty($gpon_id)){
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		//参团之前的验证： 团购配置状态 团购有效时间 是否达到参团上限 是否已经参加该团
		$setting = D('GrouponSetting');
		$set_info = $setting->where("set_id = ".$set_id." and status = 1")->find();
		if(empty($set_info)){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '该团购已经下线.';
			$this->ajaxReturn($response);
		}
		if(!empty($set_info['start_time'])&&date("Y-m-d H:i:s")<$set_info['start_time']){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '团购尚未开始..';
			$this->ajaxReturn($response);
		}
		if(empty($set_info['death_time']) || date("Y-m-d H:i:s")>$set_info['death_time']){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '团购已经结束...';
			$this->ajaxReturn($response);
		}
		$grouponDetail = D('GrouponDetail');
		$db_res = $grouponDetail->query("select * from ar_shop.groupon_detail as gd 
									left join ar_shop.groupon_info as gi on gi.gpon_id = gd.gpon_id
									where gi.set_id = ".$set_id." and user_id = '".$user_id."'");
		if(count($db_res)>=num_f($set_info['max_join'])){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '参团失败，您已经超过参团限额';
			$this->ajaxReturn($response);
		}
		// if($db_res[0]['status']==1){
			// $response['rsc'] = C('RESPONSE.FAILED');
			// $response['msg'] = '参团失败，该团已满';
			// $this->ajaxReturn($response);
		// }
		$db_res = $grouponDetail->where("gpon_id = '".$gpon_id."' and user_id = '".$user_id."'")->select();
		if(!empty($db_res)){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '您已经参与该团;';
			$this->ajaxReturn($response);
		}
		//验证成功 执行参团操作
		$grouponInfo = D('GrouponInfo');
		$gInfo = $grouponInfo->where("gpon_id = '".$gpon_id."'")->find();
		if($gInfo['status']>0){
			$response['rsc'] = C('RESPONSE.FAILED');
			$response['msg'] = '该团已经满员';
			$this->ajaxReturn($response);
		}
		$grouponInfo->joinGpon($user_id,$gpon_id,$set_info);
		$response['data'] = $gpon_id;
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$response['msg'] = '参团成功';
		$this->ajaxReturn($response);
	}
	
	// 前一个月
	public function ajaxMyGponList() {
		if($this->checkLogin()==false){
			$response['msg'] = '尚未登陆';
			$response['toLogin'] = 1;
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id = $this->uId();
		$grouponInfo = D('GrouponInfo');
		$list = $grouponInfo->myGponList($user_id);
		// dump($list);exit;
		$gponSetting = D('GrouponSetting');
		$db_res = $gponSetting->where("status = 1 and death_time > '".date("Y-m-d H:i:s")."'")->select();
		$buttons = array();
		if(!empty($db_res)){
			foreach($db_res as $db_one){
				$button['set_id'] = $db_one['set_id'];
				$button['set_alias'] = $db_one['set_alias'];
				$buttons[] = $button;
			}
		}
		$response['data'] = $list;
		$response['buttons'] = $buttons;
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$response['msg'] = '获取成功';
		$this->ajaxReturn($response);
		
	}
	
	// 前20个
	public function ajaxHotGponList() {
		$set_id = I('set_id');
		if(empty($set_id)){
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$grouponInfo = D('GrouponInfo');
		$list = $grouponInfo->hotGponList($set_id);
		// dump($list);exit;
		$response['data'] = $list;
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$response['msg'] = '获取成功';
		$this->ajaxReturn($response);
	}
	
	//获取团购结算详情接口
	public function ajaxGetGponCartOrder(){
		$data = array();
		if($this->checkLogin()==false){
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id = $this->uId();
		$set_id = I('set_id');
		$gpon_id = I('gpon_id');
		if(empty($set_id)||empty($gpon_id)){
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		//获取配置
		$setting = D('GrouponSetting');
		$set_info = $setting->where("set_id = ".$set_id." and status = 1")->find();
		if(empty($set_info)){
			$response['msg'] = '该团购已经售罄下架';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		//查询该用户团购订单
		$orderInfo = D('OrderInfo');
		$db_res = $orderInfo->where("user_id = '".$user_id."' and order_type = 'groupon' and order_status <> 20 and promote_id = '".$set_id."'")->select();
		if(!empty($db_res)){
			if(count($db_res) >= num_f($set_info['buy_limit'])){
				$response['msg'] = '您已经超过下单数量限制';
				$response['rsc'] = C('RESPONSE.FAILED');
				$this->ajaxReturn($response);
			}
			foreach($db_res as $db_one){
				if($db_one['promote_code']==$gpon_id){
					$response['toOrderList'] = 1;
					$response['msg'] = '该团购订单已经生成，正在跳转至订单列表';
					$response['rsc'] = C('RESPONSE.SUCCESS');
					$this->ajaxReturn($response);
				}
			}
		}
		
		$cart_list = $this->formatCartList($gpon_id,$set_info,$user_id);
		$res = $this->commodityLimitSrv->checkLimit($set_info['commodity_id'],1,2);
		if($res==false){
			$response['msg'] = '该团购商品已经售罄';
			$response['rsc'] = C('RESPONSE.SUCCESS');
			$this->ajaxReturn($response);
		}
		
		$sale_cycle = $this->commoditySrv->hitLastSaleCycle($set_info['commodity_id']);
		$data['cart_list'] = $cart_list;
		$data['sale_cycle'] = $sale_cycle;
		//获取默认配送地址
		$userDeliveryAddress = D('UserDeliveryAddress');
		$db_res = $userDeliveryAddress->where("user_id = '".$user_id."' and firstaddress = 1")->find();
		if(!empty($db_res)){
			$data['firstaddress'] = $db_res;
		}else{
			$data['firstaddress'] = null;
		}
		$data['shipping_fee'] = $set_info['ship_fee'];
		$response['data'] = $data;
		$response['msg'] = $res['msg'];
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}
	
	//提交订单接口
	public function ajaxAddGponOrder(){
		if($this->checkLogin()==false){
			$response['msg'] = '尚未登陆';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$user_id = $this->uId();
		$set_id = I('set_id',null);
		$gpon_id = I('gpon_id',null);
		$uda_id = I('uda_id',null);
		$dispatch_datetime = I('dispatch_datetime',null);
		if(empty($dispatch_datetime) || empty($uda_id)){
			$response['msg'] = '参数异常';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		//获取配置
		$setting = D('GrouponSetting');
		$set_info = $setting->where("set_id = ".$set_id." and status = 1")->find();
		if(empty($set_info)){
			$response['msg'] = '该团购已经售罄下架';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		$cart_list = $this->formatCartList($gpon_id,$set_info,$user_id);
		$order = D('OrderInfo');
		$res = $order->addGrouponOrder($cart_list,$user_id,$dispatch_datetime,$uda_id,$set_id,$gpon_id,$set_info['ship_fee']);
		if($res['isok'] == false){
			$response['msg'] = $res['msg'];
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		
		// 默认微信支付
		$paymentOnlineFlow = D('PaymentOnlineFlow');
		$data['flow_id'] = new_doc_id('ONLINE_FLOW');
		$data['type'] = 0;
		$data['status'] = 0;
		$data['relation_id'] = $res['payment_id'];
		$data['should_pay'] = $res['should_payment'];
		$paymentOnlineFlow->data($data)->add();
		
		
		$response['order_id'] = $res['order_id'];
		$response['href'] = C('HTTP_DOMAIN')."/Home/Wxmpay/index?flow_id=".$data['flow_id'];
		$response['msg'] = '下单成功';
		$response['rsc'] = C('RESPONSE.SUCCESS');
		$this->ajaxReturn($response);
	}
	
	public function formatImgs($imgs){
		$imgs = explode('|',$imgs);
		$res = array();
		foreach($imgs as $img){
			$res[] = C('HTTP_IMG').$img;
		}
		return $res;
	}
	
	public function formatCartList($gpon_id,$set_info,$user_id){
		$people_num = $this->grouponSrv->getGponPeopleNum($gpon_id);
		$hit_price = $this->grouponSrv->hitGponPrice($set_info['price_gradient'],$people_num);
		if($hit_price<0){
			$response['msg'] = '团购价格命中错误';
			$response['rsc'] = C('RESPONSE.FAILED');
			$this->ajaxReturn($response);
		}
		//判断是否是团长
		$db_res = $this->grouponSrv->where("gpon_id = '".$gpon_id."' and organiser = '".$user_id."'")->find();
		if(!empty($db_res)){//团长
			$hit_price = $hit_price-num_f($set_info['organiser_welfare']);
		}
		$commodity_info = $this->commoditySrv->commodity_info($set_info['commodity_id']);
		$commodity['commodity_id'] = $set_info['commodity_id'];
		$commodity['commodity_num'] = 1;
		$commodity['commodity_type'] = 'groupon';
		$commodity['name'] = $commodity_info['name'];
		$commodity['sale_price'] = $hit_price;
		$commodity['unit_name'] = C('GOODS_UNIT_NAME.'.$commodity_info['unit_id']);
		$commodity['spec'] = $commodity_info['spec'];
		$commodity['brief_pic'] = $commodity_info['brief_pic'];
		$commodity['brief_sum'] = num_f($commodity['sale_price'])*$commodity['commodity_num'];
		$commodity['index'] = $set_info['commodity_id'].'_groupon';
		$new_commoditys[] = $commodity;
		$cart_list['list'] = $new_commoditys;
		$cart_list['sum']['commodity_sum'] = $commodity['commodity_num'];
		$cart_list['sum']['sale_sum'] = $commodity['brief_sum'];
		return $cart_list;
	}
	
};